/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BindMobileActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import io.bhex.app.R;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.utils.CommonUtil;
import io.bhex.sdk.account.bean.MobileCodeListBean;
import io.bhex.app.account.presenter.BindMobilePresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.app.safe.DeepKnowVerify;
import io.bhex.app.safe.DeepSEListener;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.view.InputView;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;

/**
 * ================================================
 * 描   述：绑定手机或者邮箱
 * ================================================
 */

public class BindMobileActivity extends BaseActivity<BindMobilePresenter,BindMobilePresenter.BindMobileUI> implements BindMobilePresenter.BindMobileUI, View.OnClickListener {
    private InputView inputMobile;
    private InputView inputVerifyMobile;
    private InputView inputVerifyEmail;
    private InputView inputAccount;
    private DeepKnowVerify deepKnowVerify;
    private TextView nationalCode;
    private TextView sendVerifyCodeTvOfEmail;
    private TextView sendVerifyCodeTvOfMobile;

    @Override
    protected int getContentView() {
        return R.layout.activity_bind_mobile_layout;
    }

    @Override
    protected BindMobilePresenter createPresenter() {
        return new BindMobilePresenter();
    }

    @Override
    protected BindMobilePresenter.BindMobileUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        deepKnowVerify = DeepKnowVerify.getInstance(this);
        inputMobile = viewFinder.find(R.id.moble_input);
        inputMobile.setPaddingLeft(PixelUtils.dp2px(68));
        inputAccount = viewFinder.find(R.id.account_input);
        nationalCode = viewFinder.textView(R.id.mobile_code);
        inputVerifyMobile = viewFinder.find(R.id.mobile_verify_code_et);
        inputVerifyMobile.setPaddingRight(PixelUtils.dp2px(80));
        inputVerifyEmail = viewFinder.find(R.id.email_verify_code_et);
        inputVerifyEmail.setPaddingRight(PixelUtils.dp2px(80));
        sendVerifyCodeTvOfEmail = viewFinder.textView(R.id.get_email_verify_code);
        sendVerifyCodeTvOfMobile = viewFinder.textView(R.id.get_mobile_verify_code);
        UserInfoBean userInfo = UserInfo.getUserInfo();
        if (userInfo != null) {
            if (userInfo.getRegisterType()==1) {
                String mobile = userInfo.getMobile();
                inputAccount.setInputString(mobile);
            }else{
                String email = userInfo.getEmail();
                inputAccount.setInputString(email);
            }
        }

        setDefaultMobileCode();
    }

    private void setDefaultMobileCode() {
        String defaultMobileCode = CommonUtil.getDefaultMobileCode(this);
        if (!TextUtils.isEmpty(defaultMobileCode)) {
            nationalCode.setText("+"+defaultMobileCode);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        deepKnowVerify.ignoreDPView(viewFinder.find(R.id.get_mobile_verify_code),"bindMobile");
        viewFinder.find(R.id.mobile_code_linear).setOnClickListener(this);
        viewFinder.find(R.id.get_mobile_verify_code).setOnClickListener(this);
        viewFinder.find(R.id.get_email_verify_code).setOnClickListener(this);
        viewFinder.find(R.id.btn_sure).setOnClickListener(this);


        inputMobile.addTextWatch(mTextWatcher);
        inputVerifyEmail.addTextWatch(mTextWatcher);
        inputVerifyMobile.addTextWatch(mTextWatcher);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mobile_code_linear:
                //选择国家区号
                IntentUtils.goMobileCodeList(this, Fields.REQUEST_CODE_BIND, Fields.FIELD_COUNTRY_PARAM_TYPE_AREA_CODE);

                break;
            case R.id.get_mobile_verify_code:
                final String mobile = inputMobile.getInputString();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.input_phone_number));
                    return;
                } else {
                    inputMobile.setError("");
                }
                if (!NetWorkStatus.isConnected(this)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.hint_network_not_connect));
                    return;
                }

                if (!NetWorkStatus.isConnected(this)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.hint_network_not_connect));
                    return;
                }
                getUI().showProgressDialog("","");
                deepKnowVerify.verify(baseSEListener);

                break;
            case R.id.get_email_verify_code:
                getPresenter().sendEmailCode();

                break;
            case R.id.btn_sure:
                String mobile2 = inputMobile.getInputString();
                if (TextUtils.isEmpty(mobile2)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.input_phone_number));
                    return;
                } else {
                    inputMobile.setError("");
                }
                String mobileCode = inputVerifyMobile.getInputString();
                if (TextUtils.isEmpty(mobileCode)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.string_input_mobile_verify_code));
                    return;
                } else {
                    inputVerifyMobile.setError("");
                }

                String emailCode = inputVerifyEmail.getInputString();
                if (TextUtils.isEmpty(emailCode)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.string_input_email_verify_code));
                    return;
                } else {
                    inputVerifyEmail.setError("");
                }

                if (!NetWorkStatus.isConnected(this)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.hint_network_not_connect));
                    return;
                }
                String nationCode = nationalCode.getText().toString().replace("+", "");
                getPresenter().requestBindMobile(nationCode,mobile2,emailCode,mobileCode);
                break;
        }
    }

    private DeepSEListener baseSEListener = new DeepSEListener() {

        /**
         * SDK内部show loading dialog
         */
        @Override
        public void onShowDialog() {
            getUI().dismissProgressDialog();
        }

        @Override
        public void onError(String errorCode, String error) {
//            DebugLog.i(TAG,"onError-->errorCode:"+errorCode+", error: "+error);
//            ToastUtils.showShort(error);
            getUI().dismissProgressDialog();
            ToastUtils.showShort(getString(R.string.string_net_exception)+errorCode);
        }

        /**
         * 验证码Dialog关闭
         * 1：webview的叉按钮关闭
         * 2：点击屏幕外关闭
         * 3：点击回退键关闭
         *
         * @param num
         */
        @Override
        public void onCloseDialog(int num) {
//            DebugLog.i(TAG, "onCloseDialog-->" + num);
        }

        /**
         * show 验证码webview
         */
        @Override
        public void onDialogReady() {
//            DebugLog.i(TAG,"onDialogReady-->SDK show captcha webview dialog! ");
        }

        /**
         * 验证成功
         * @param token
         */
        @Override
        public void onResult(String token) {
//            DebugLog.i(TAG,"onResult: "+token);
            final String mobile = inputMobile.getInputString();
            if (TextUtils.isEmpty(mobile)) {
                ToastUtils.showShort(BindMobileActivity.this,getResources().getString(R.string.input_phone_number));
                return;
            } else {
                inputMobile.setError("");
            }
            if (!NetWorkStatus.isConnected(BindMobileActivity.this)) {
                ToastUtils.showShort(BindMobileActivity.this,getResources().getString(R.string.hint_network_not_connect));
                return;
            }
            String nationCode = nationalCode.getText().toString().replace("+", "");
            getPresenter().requestMobileCode(nationCode,mobile,token);

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deepKnowVerify.destroy();
    }

    @Override
    public void setAuthTv(boolean isEmail,String s) {
        if (isEmail) {
            sendVerifyCodeTvOfEmail.setText(s);
        }else{
            sendVerifyCodeTvOfMobile.setText(s);
        }
    }

    @Override
    public void setAuthTvStatus(boolean isEmail,boolean b) {
        if (isEmail) {
            sendVerifyCodeTvOfEmail.setEnabled(b);
            sendVerifyCodeTvOfEmail.setTextColor(b ? getResources().getColor(R.color.blue) : SkinColorUtil.getDark50(this));
        }else{
            sendVerifyCodeTvOfMobile.setEnabled(b);
            sendVerifyCodeTvOfMobile.setTextColor(b ? getResources().getColor(R.color.blue) : SkinColorUtil.getDark50(this));
        }
    }

    /**
     * 编辑框监听器
     */
    private TextWatcher mTextWatcher = new TextWatcher() {

        /** 改变前*/
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        /** 内容改变*/
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            if (getPresenter().checkInputContentIsEmpty(inputMobile,inputVerifyEmail,inputVerifyMobile)) {
                viewFinder.find(R.id.btn_sure).setEnabled(true);
            } else {
                viewFinder.find(R.id.btn_sure).setEnabled(false);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Fields.REQUEST_CODE_BIND && resultCode == RESULT_OK) {
            MobileCodeListBean.MobileCodeBean mobileCodeBean = (MobileCodeListBean.MobileCodeBean) data.getSerializableExtra(Fields.INTENT_MOBILE_CODE);
            if (mobileCodeBean != null) {
                String countryCode = mobileCodeBean.getNationalCode();
                if (!TextUtils.isEmpty(countryCode)) {
                    nationalCode.setText("+" + countryCode);
                }
            }
        }
    }

}
